package com.mall.web.util;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class PinYinUtil {
	public static String getPinYinFromChinese(String chinese) {

		if (StringUtils.isBlank(chinese)) {
			return "";
		}

		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		// UPPERCASE：大写 (ZHONG)
		// LOWERCASE：小写 (zhong)
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);

		// WITHOUT_TONE：无音标 (zhong)
		// WITH_TONE_NUMBER：1-4数字表示英标 (zhong4)
		// WITH_TONE_MARK：直接用音标符（必须WITH_U_UNICODE否则异常） (zhòng)
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

		// WITH_V：用v表示ü (nv)
		// WITH_U_AND_COLON：用"u:"表示ü (nu:)
		// WITH_U_UNICODE：直接用ü (nü)
		format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < chinese.length(); i++) {
			try {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(chinese.charAt(i), format);
				Set<String> set = new HashSet<>();
				for (int j = 0; j < pinyin.length; j++) {
					set.add(pinyin[j]);
				}
				Iterator<String> it = set.iterator();
				while (it.hasNext()) {
					String str = it.next();
					sb.append(str);
				}
			} catch (Exception e) {
				System.out.println(chinese);
			}

		}
		return sb.toString();
	}
}
